let arr = [
    {
        title:'爷爷1',
        id:1,
        pid:3
    },
    {
        title:'爷爷2',
        id:2,
        pid:4,
        children:[
            {
                title:'儿子1',
                id:4,
                pid:5
            },
            {
                title:'儿子2',
                id:4,
                pid:6,
                children:[
                   {
                    title:'孙子',
                    id:6
                   }
                ]
            }
        ]
    }
]

// console.log(arr);

// 遍历数组中的每一项，如果某一项中有children属性，就接着遍历，将遍历出来的每一项放入新数组中

function dataFlattening1(arr1){
    let newArr =  []

    function dataFlattening2(arr2){
        arr2.forEach(item => {
            if(item.children){
                dataFlattening2(item.children)
            }
            newArr.push({
                id:item.id,
                title:item.title,
                pid:item.pid ?? ''
            })
        })
    }
   
    dataFlattening2(arr1)


    return newArr
}

let res = dataFlattening1(arr)
// console.log(res);














// 0: {id: 1, title: '爷爷1', pid: 3}
// 1: {id: 4, title: '儿子1', pid: 5}
// 2: {id: 6, title: '孙子', pid: ''}
// 3: {id: 4, title: '儿子2', pid: 6}
// 4: {id: 2, title: '爷爷2', pid: 4}
function converTree(repeatArr){
    let tree = []
    repeatArr.forEach(item => {
        // 查找自己的父节点
        let parent = repeatArr.find(v => item.pid === v.id)

        if(parent){
            if(!parent.children){
                parent.children = []
            }
            parent.children.push(item)
        }else{
            tree.push(item)
        }
        
    })

   

    return tree

}

let res2 = converTree(res)

console.log(res2);




